import debounce from "@/utils/debounce"
import { ElMessage, ElNotification } from "element-plus"
import { computed, ref } from "vue"
import { DrawingFormProps, getImages } from "./components/type"
import { APIXmindAdd } from "./api"
import MindMapUtil from "./utils/mind-map"
import Loading from "./utils/loading"

export type CoverType = "plaza" | "data"

export interface ImageListProps {
  path: string
  name: string
}

export interface PaginationProps {
  page: number
  pageSize: number
  count: number
}

const PAGE_SIZE = 20
export default function useCover() {
  const pagination = ref<PaginationProps>({
    page: 1,
    pageSize: 0,
    count: 0
  })
  const imgCurrentIndex = ref<number>(-1)
  const submitLoading = ref<boolean>(false)
  const loading = ref<boolean>(false)
  const plazaLoading = ref<boolean>(false)
  const dataLoading = ref<boolean>(false)
  const vocabularyList = ref<string[]>([""])
  const imageList = ref<ImageListProps[]>([])
  const cmdForm = ref<DrawingFormProps>({
    messages: "",
    scene: "",
    model: "base",
    name: ""
  })

  // 页数
  const pageCount = computed(() => {
    return Math.ceil(pagination.value.count / PAGE_SIZE)
  })

  const getImageList = () => {
    getImages()
      .then((imgs: any) => {
        imageList.value = imgs
      })
      .catch((error) => {
        console.error("获取图片列表时发生错误：", error)
      })
  }

  const handleChangeImg = debounce((item: any, index: number) => {
    imgCurrentIndex.value = index
    cmdForm.value.scene = item.name
  }, 200)

  const handleSubmit = debounce(async () => {
    try {
      if (MindMapUtil.instance.creating) {
        ElNotification({
          message: "正在生成"
        })
        return
      }
      submitLoading.value = true
      // 先触发socket, 再调用submit接口
      // await Speech.instance.getDoPic(cmdForm.value.command)

      MindMapUtil.instance.creating = true
      const res = await APIXmindAdd(cmdForm.value)
      // if (res.)
      if (res.code === 200) {
        MindMapUtil.instance.currentId = res.data.xmind_id
        ElMessage({
          type: "success",
          message: "提交成功"
        })
        Loading.show()
        MindMapUtil.instance.mindMap?.setMode("edit")
        MindMapUtil.instance.creating = false
        // 清空表单
        cmdForm.value = {
          messages: "",
          scene: "",
          model: "base",
          name: ""
        }
        imgCurrentIndex.value = -1
        vocabularyList.value = [""]
      }
    } catch (error: any) {
      console.error("error", error)
      ElMessage({
        message: error.message || "提交失败",
        type: "error"
      })
    } finally {
      MindMapUtil.instance.creating = false
      submitLoading.value = false
    }
  }, 300)

  return {
    loading,
    pagination,
    pageCount,
    imgCurrentIndex,
    submitLoading,
    vocabularyList,
    imageList,
    cmdForm,
    plazaLoading,
    dataLoading,
    getImageList,
    handleChangeImg,
    handleSubmit
  }
}
